﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Framework.Logic.Web;

namespace Framework.Logic.Settings
{
    public class ServerProperties
    {

        public ServerProperties(string directoryPath)
        {
            string propertiesFile = directoryPath + "\\server.properties";

            if (!File.Exists(propertiesFile))
            {
                return;
            }

            using (var fs = new FileStream(propertiesFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var sr = new StreamReader(fs))
                {
                    while (!sr.EndOfStream)
                    {
                       var line = sr.ReadLine();
                       if (line.Contains("server-port="))
                       {
                           Port = line.Replace("server-port=", "");
                           if (string.IsNullOrEmpty(Port))
                               Port = "25565";
                           continue;
                       }
                       else if (line.Contains("server-ip="))
                       {
                           Hostname = line.Replace("server-ip=", "");
                           if (string.IsNullOrEmpty(Hostname))
                           {
                               Hostname = GetIPAddress();
                           }
                           continue;
                       }
                       else if (line.Contains("max-players="))
                       {
                           MaxPlayers = Convert.ToInt32(line.Replace("max-players=", ""));
                       }
                    }
                }
            }
            if (string.IsNullOrEmpty(Hostname))
                Hostname = GetIPAddress();

            if (string.IsNullOrEmpty(Port))
                Port = "25565";
        }

        public string Port { get; set; }
        public string Hostname { get; set; }
        public int MaxPlayers { get; set; }

        public string GetIPAddress()
        {
            HTTPGet req = new HTTPGet();
            req.Request("http://checkip.dyndns.org");
            string[] a = req.ResponseBody.Split(':');
            string a2 = a[1].Substring(1);
            string[] a3 = a2.Split('<');
            return a3[0];
        }
    }
}
